<?php

namespace backend\models;
use yii\helpers\ArrayHelper;
use Yii;

/**
 * This is the model class for table "{{%menu}}".
 *
 * @property int $id
 * @property string $name
 * @property int $parent
 * @property string $route
 * @property int $order
 * @property resource $data
 * @property int $type
 *
 * @property Menu $parent0
 * @property Menu[] $menus
 */
class Menu extends \yii\db\ActiveRecord
{
    static $_parentMenu;   // 缓存所有，有子菜单的菜单
    /**
     * @inheritdoc
     */
    /**
     *保存所有的菜单数据的数据，KEY是菜单的type
     * @var Array 
     */
    static $_allMenu;  
    public static function tableName()
    {
        return '{{%menu}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['parent', 'order', 'type'], 'integer'],
            [['data'], 'string'],
            [['name'], 'string', 'max' => 128],
            [['route','icon'], 'string', 'max' => 255],
            [['parent'], 'exist', 'skipOnError' => true, 'targetClass' => Menu::className(), 'targetAttribute' => ['parent' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', 'ID'),
            'name' => Yii::t('common', 'Menu Name'),
            'parent' => Yii::t('common', 'Parent Menu'),
            'route' => Yii::t('common', 'Route'),
            'order' => Yii::t('common', 'Order'),
            'data' => Yii::t('common', 'Data'),
            'type' => Yii::t('common', 'Type'),
        ];
    }

    /**
     *  判断菜单是否有子菜单
     * @param int $id  菜单ID
     * @return boolean 返回true 证明当前菜单拥有子菜单
     */
    static function subMenu($id){
        if(!self::$_parentMenu){
            self::$_parentMenu = Yii::$app->db->createCommand(
                    "SELECT t1.parent From sshop_menu as t1,sshop_menu as t2 where t1.parent = t2.id GROUP BY t1.parent"
            )->queryColumn();
        }
        return in_array($id,self::$_parentMenu);
    }
    
    static function getNode($type,$root = null ,$tag = '|_'){
        $data = self::getAllMenu($type);
        $nodes = [];
        foreach($data as $k => $v){
            if($v['parent'] === $root){
                $nodes[$v['id']] =  $tag.$v['name'];
                $subNodes = self::getNode($type,$v['id'],$tag.'__');
                $nodes = ArrayHelper::merge($nodes,$subNodes);
            }
        }
        return $nodes;
    }
    
    static function getAllMenu($type){
        if(!self::$_allMenu[$type]){
            self::$_allMenu[$type] = Menu::find()->where(['type' => $type])->asArray()->all();
        }
        return self::$_allMenu[$type];
    }
}
